package bs.util;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

/**
 * 
 * Log:
 *
 * @author 姜治昊
 * @time 2017年11月3日 上午10:39:39
 */
public class Log {
	
	private static String logPath;
	
	private static BufferedWriter bw;
	
	public static void init() {
		init("log"+(new Date())+".log");
	}
	
	public static void init(String fileName) {
		if(null == bw) {
			try {
				InputStream in = Log.class.getClassLoader().getResourceAsStream("prop/config.properties");
				Properties p = new Properties();
				p.load(in);
				logPath = p.get("redisCache_filePath").toString();
				bw = new BufferedWriter(new FileWriter(logPath+fileName,true));
			} catch(FileNotFoundException fe) {
				fe.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 
	 * @param s
	 * @param stop 是否结束日志工作
	 */
	public static void log(String s ,boolean stop) {
		if(bw == null) {
			throw (new RuntimeException("日志类需要初始化..."));
		}
		try {
			bw.write(s);
			bw.newLine();
			bw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(stop) {
				destroy(bw);
			}
		}
	}
	
	/**
	 * 关闭流
	 * @param bw
	 */
	private static void destroy(BufferedWriter bw) {
		if(bw != null) {
			try {
				bw.close();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 判断日志是否已经初始化
	 * @return
	 */
	public static boolean isInint() {
		if(null != bw) {
			return true;
		}
		return false;
	}
	
}
